import axios from 'axios'
import type { AxiosResponse } from 'axios'

// 后端通用响应格式
interface ApiResponse<T> {
  code: number
  msg: string
  data: T
}

// 定义API响应数据类型 - 匹配后端DashboardDTO
interface DashboardData {
  stats: Array<{
    title: string
    value: number
    icon: string
    trend: number
  }>
  charts: {
    line: {
      labels: string[]
      datasets: Array<{
        name: string
        values: number[]
        color?: string
      }>
    }
    bar: {
      labels: string[]
      datasets: Array<{
        name: string
        values: number[]
        color?: string
      }>
    }
  }
  table: Array<Record<string, any>>
}

// 仪表盘实体类型 - 匹配后端Dashboard实体
interface Dashboard {
  id: number
  title: string
  description: string
  config: string
  creatorId: number
  isPublic: boolean
  createTime: string
  updateTime: string
}

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '',
  timeout: 10000,
  // 添加跨域支持
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
})

// 模拟数据
const mockDashboardData: DashboardData = {
      stats: [
        { title: '总报告数', value: 128, icon: 'file', trend: 0 },
        { title: '今日新增', value: 12, icon: 'plus', trend: 2.5 },
        { title: '完成率', value: 85, icon: 'check', trend: 1.2 },
        { title: '平均得分', value: 92, icon: 'star', trend: -0.8 }
      ],
      charts: {
        line: {
          labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
          datasets: [
            {
              name: '报告数量',
              values: [120, 190, 170, 210, 230, 250],
              color: '#409EFF'
            }
          ]
        },
        bar: {
          labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          datasets: [
            {
              name: '活跃用户',
              values: [120, 200, 150, 80, 70, 110, 130],
              color: '#67C23A'
            }
          ]
        }
      },
      table: [
        { id: 1, title: '月度销售报告', author: '张三', date: '2023-07-15', status: '已完成' },
        { id: 2, title: '季度财务分析', author: '李四', date: '2023-07-10', status: '进行中' },
        { id: 3, title: '市场调研报告', author: '王五', date: '2023-07-05', status: '已完成' },
        { id: 4, title: '产品用户反馈', author: '赵六', date: '2023-07-01', status: '已完成' },
        { id: 5, title: '年度战略规划', author: '钱七', date: '2023-06-28', status: '审核中' }
      ]
}

// 添加响应拦截器模拟数据
api.interceptors.response.use(
  response => {
    return response
  },
  error => {
    // 始终返回模拟数据，不管是什么错误
    const config = error.config || {}
    
    // 模拟仪表盘数据接口
    if (config.url === '/report') {
      console.info('使用模拟仪表盘数据')
      return Promise.resolve({
        data: {
          code: 200,
          msg: 'success',
          data: mockDashboardData
        },
        status: 200,
        statusText: 'OK',
        headers: {},
        config
      })
    }
    
    // 模拟仪表盘列表接口
    if (config.url === '/api/dashboard/public' || (config.url && config.url.includes('/api/dashboard/user/'))) {
      console.log('返回模拟仪表盘列表数据')
      return Promise.resolve({
        data: {
          code: 200,
          msg: 'success',
          data: [
            {
              id: 1,
              title: '销售数据分析',
              description: '展示销售数据趋势和分布',
              config: JSON.stringify(mockDashboardData),
              creatorId: 1,
              isPublic: true,
              createTime: '2023-07-01 00:00:00',
              updateTime: '2023-07-15 00:00:00'
            },
            {
              id: 2,
              title: '用户增长分析',
              description: '展示用户增长趋势和渠道分布',
              config: JSON.stringify(mockDashboardData),
              creatorId: 1,
              isPublic: true,
              createTime: '2023-07-05 00:00:00',
              updateTime: '2023-07-10 00:00:00'
            }
          ]
        },
        status: 200,
        statusText: 'OK',
        headers: {},
        config
      })
    }
    
    // 对于其他API调用，返回默认错误响应
    return Promise.reject(error)
  }
)

// 获取仪表盘数据
export const fetchDashboardData = async (): Promise<DashboardData> => {
  try {
    const response = await api.get<ApiResponse<DashboardData>>('/report')
    if (response.data && response.data.code === 200) {
      return response.data.data
    } else {
      // 返回模拟数据
      return mockDashboardData
    }
  } catch (error) {
    // 返回模拟数据，不抛出异常
    return mockDashboardData
  }
}

// 获取用户的仪表盘列表
export const getUserDashboards = async (userId: number): Promise<Dashboard[]> => {
  try {
    const response = await api.get<ApiResponse<Dashboard[]>>(`/api/dashboard/user/${userId}`)
    if (response.data && response.data.code === 200) {
      return response.data.data
    } else {
      throw new Error('获取用户仪表盘列表失败')
    }
  } catch (error) {
    console.error('获取用户仪表盘列表失败', error)
    return []
  }
}

// 获取公共仪表盘列表
export const getPublicDashboards = async (): Promise<Dashboard[]> => {
  try {
    const response = await api.get<ApiResponse<Dashboard[]>>('/api/dashboard/public')
    if (response.data && response.data.code === 200) {
      return response.data.data
    } else {
      throw new Error('获取公共仪表盘列表失败')
    }
  } catch (error) {
    console.error('获取公共仪表盘列表失败', error)
    return []
  }
}

// 获取仪表盘详情
export const getDashboardById = async (id: number): Promise<Dashboard> => {
  try {
    const response = await api.get<ApiResponse<Dashboard>>(`/api/dashboard/${id}`)
    if (response.data && response.data.code === 200) {
      return response.data.data
    } else {
      throw new Error('获取仪表盘详情失败')
    }
  } catch (error) {
    console.error('获取仪表盘详情失败', error)
    throw error
  }
}

// 保存仪表盘
export const saveDashboard = async (dashboard: Omit<Dashboard, 'id' | 'createTime' | 'updateTime'>): Promise<boolean> => {
  try {
    const response = await api.post<ApiResponse<boolean>>('/api/dashboard', dashboard)
    return response.data && response.data.code === 200 && response.data.data
  } catch (error) {
    console.error('保存仪表盘失败', error)
    return false
  }
}

// 更新仪表盘
export const updateDashboard = async (dashboard: Dashboard): Promise<boolean> => {
  try {
    const response = await api.put<ApiResponse<boolean>>('/api/dashboard', dashboard)
    return response.data && response.data.code === 200 && response.data.data
  } catch (error) {
    console.error('更新仪表盘失败', error)
    return false
  }
}

// 删除仪表盘
export const deleteDashboard = async (id: number): Promise<boolean> => {
  try {
    const response = await api.delete<ApiResponse<boolean>>(`/api/dashboard/${id}`)
    return response.data && response.data.code === 200 && response.data.data
  } catch (error) {
    console.error('删除仪表盘失败', error)
    return false
  }
}
